package com.pkx.guide.qianfeng.service.impl;

import com.pkx.guide.common.util.StringUtils;
import com.pkx.guide.qianfeng.service.QianFengPlayLedService;
import com.pkx.guide.qianfeng.service.QianFengSocketService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.nio.charset.StandardCharsets;

@Service
@Slf4j
public class QianFengPlayLedServiceImpl implements QianFengPlayLedService {

    @Resource
    private QianFengSocketService qianFengSocketService;

    /**
     * 控制led
     *
     * @param jsonStr
     * @param ip
     * @param port
     * @return
     */
    @Override
    public String controlLed(String ip, Integer port, String jsonStr) throws Exception {
        if (StringUtils.isEmpty(jsonStr)) {
            return null;
        }
        log.error("led请求参数ip：{}",ip);
        log.error("led请求参数port：{}",port);
        log.error("led请求参数：{}", jsonStr);
        Socket   socket = null;
        String result= null;
        try {
            // 创建连接
            socket = qianFengSocketService.creates(ip, port);
            if (socket  == null || socket.isClosed()) {
                log.error("创建socket连接失败或连接已关闭，ip:{}，port:{}", ip, port);
                return null;
            }

            // 关键：设置读取超时时间（根据设备响应速度调整，建议 60 秒）
            byte[] params = jsonStr.getBytes(StandardCharsets.UTF_8);

            qianFengSocketService.send(params, socket);
            byte[]  resultArr = qianFengSocketService.receive(socket);

            if (resultArr == null) {
                log.error("led设备无响应，未接收到数据，ip:{}", ip);
                return null;
            }
            log.info("led响应结果：{}", resultArr);
        } catch (SocketTimeoutException e) {
            // 单独捕获超时异常，记录更详细的日志
            log.error("led请求超时（{}秒），ip:{}，请检查设备响应速度或网络", 8, ip);
        } catch (Exception e) {
            log.error("led请求失败：{}，ip:{}", e.getMessage(), ip);
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    log.error("关闭socket失败：{}", e.getMessage());
                }
            }
        }
        return result;
    }

    @Override
    public byte[] controlLeds(String ip, Integer port, byte[] jsonStr) throws Exception {
      if (jsonStr == null){
          return null;
      }
        log.info("led请求参数：{}", jsonStr);
        Socket socket = null;
        byte[] result = null;
        try {
            // 创建连接
            socket = qianFengSocketService.creates(ip, port);
            if (socket == null || socket.isClosed()) {
                log.error("创建socket连接失败或连接已关闭，ip:{}，port:{}", ip, port);
                return null;
            }

            // 关键：设置读取超时时间（根据设备响应速度调整，建议 60 秒）


            qianFengSocketService.send(jsonStr, socket);
            byte[] resultArr = qianFengSocketService.receive(socket);

            log.error("resultArr内容（十六进制）:{}", resultArr);
            if (resultArr == null) {
                log.error("led设备无响应，未接收到数据，ip:{}", ip);
                return null;
            }
            result = resultArr;
            log.info("led响应结果：{}", result);
        } catch (SocketTimeoutException e) {
            // 单独捕获超时异常，记录更详细的日志
            log.error("led请求超时（{}秒），ip:{}，请检查设备响应速度或网络", 8, ip);
        } catch (Exception e) {
            log.error("led请求失败：{}，ip:{}", e.getMessage(), ip);
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    log.error("关闭socket失败：{}", e.getMessage());
                }
            }
        }
        return result;
    }

}
